﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Xml;
using FineUICore;
using Kalman.Enums;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using QuDao;
using Kalman;
using Kalman.Extensions;

namespace AdminUI.Pages
{
    [Authorize]
    public class IndexModel : BaseModel
    {
        public void OnGet()
        {
            LoadData();

            ViewBag.UserType = "平台";
            var title = "渠道通";
            //var shop = ShopBO.Instance.GetItem(OnlineShopID);
            ViewBag.Title = title;
            ViewBag.HomeUrl = "~/Home/Main";

            if (OnlineUserType == 2)
            {
                ViewBag.UserType = $"【{OnlineTID}】{OnlineTenantName}";
                ViewBag.Title = $"{OnlineTenantName}";
                ViewBag.HomeUrl = "~/Home/TenantMain";
            }
            //else if(OnlineUserType == 3)
            //{
            //    ViewBag.UserType = $"【{OnlinePID}】{OnlinePartnerName}";
            //    ViewBag.Title = $"{OnlinePartnerName}";
            //    ViewBag.HomeUrl = "~/Home/Main";
            //}
        }

        #region LoadData

        private string _cookieMenuStyle = "tree";
        private bool _cookieShowOnlyBase = false;
        private string _cookieDisplayMode = "normal";
        private string _cookieMainTabs = "multi";
        private string _cookieLang = "zh_CN";
        private string _cookieSearchText = "";
        // 示例数
        private readonly int _examplesCount = 0;

        private void LoadData()
        {
            //string cookie = String.Empty;
            // 从Cookie中读取 - 是否仅显示基础版示例
            var cookie = Request.Cookies["ShowOnlyBase"];
            if (cookie != null)
            {
                _cookieShowOnlyBase = Convert.ToBoolean(cookie);
            }


            // 如果是FineUICore（基础版），或者用户选择仅显示基础版示例
            if (_cookieShowOnlyBase || Constants.IS_BASE)
            {
                // 基础版不支持紧凑模式，大字体模式，大间距模式，智能树菜单
                _cookieMenuStyle = "plaintree";
                _cookieDisplayMode = "normal";
            }
            else
            {
                // 从Cookie中读取 - 左侧菜单类型
                cookie = Request.Cookies["MenuStyle"];
                if (!String.IsNullOrEmpty(cookie))
                {
                    _cookieMenuStyle = cookie;
                }

                // 从Cookie中读取 - 显示模式
                cookie = Request.Cookies["DisplayMode"];
                if (!String.IsNullOrEmpty(cookie))
                {
                    _cookieDisplayMode = cookie;
                }
            }


            // 从Cookie中读取 - 语言
            cookie = Request.Cookies["Language"];
            if (!String.IsNullOrEmpty(cookie))
            {
                _cookieLang = cookie;
            }


            // 从Cookie中读取 - 搜索文本
            cookie = Request.Cookies["SearchText"];
            if (!String.IsNullOrEmpty(cookie))
            {
                _cookieSearchText = HttpUtility.UrlDecode(cookie);
            }

            // 从Cookie中读取 - 主选项卡标签
            cookie = Request.Cookies["MainTabs"];
            if (!String.IsNullOrEmpty(cookie))
            {
                _cookieMainTabs = cookie;
            }

            LoadTreeMenuFromDB();

            ViewBag.CookieMenuStyle = _cookieMenuStyle;
            ViewBag.CookieShowOnlyBase = _cookieShowOnlyBase;
            ViewBag.CookieIsBase = Constants.IS_BASE;
            ViewBag.CookieDisplayMode = _cookieDisplayMode;
            ViewBag.CookieMainTabs = _cookieMainTabs;
            ViewBag.CookieLang = _cookieLang;
            ViewBag.CookieSearchText = _cookieSearchText;

            ViewBag.ProductVersion = GlobalConfig.ProductVersion;
            ViewBag.ExamplesCount = _examplesCount.ToString();
            ViewBag.User = SysUserBO.Instance.GetItem<SysUser>(OnlineUserID);
        }

        #endregion

        #region 从数据库读取数据生成菜单树

        /// <summary>
        /// 创建树菜单
        /// </summary>
        /// <param name="menus"></param>
        /// <returns></returns>
        private void LoadTreeMenuFromDB()
        {
            var menus = Enumerable.Empty<NavMenu>();
            if (OnlineRoleID > 0)
            {
                //var role = RoleBO.Instance.GetItem<Role>(OnlineRoleID) ?? throw new AppException($"角色不存在：{OnlineRoleID}");
                var dic = MenuBO.Instance.GetDic(OnlineUserType);
                var list = RoleAuthorizeBO.Instance.GetListByRole(OnlineRoleID);
                //var authorizeList = new List<NavMenu>();

                foreach (var item in list)
                {
                    if (!dic.ContainsKey(item.MenuID)) continue;

                    var menu = dic[item.MenuID];
                    menus = menus.Append(new NavMenu
                    {
                        MenuID = item.MenuID,
                        MenuName = menu.MenuName,
                        MenuType = menu.MenuType,
                        ParentID = menu.ParentID,
                        Icon = menu.Icon,
                        SortFlag = menu.SortFlag,
                        Url = menu.Url,
                        IsEnable = menu.IsEnable
                    });
                }
            }
            else if (OnlineRoleID == -1) //管理员
            {
                menus = MenuBO.Instance.GetList<NavMenu>(OnlineUserType, true);//根据菜单类型获取列表
            }

            if (!menus.Any())
            {
                ShowNotify("系统管理员尚未给你配置菜单！");
                return;
            }

            //if(OnlineUserType == 3)
            //{
            //    var service = ServiceBO.Instance.GetItem<Service>(OnlineShopID, 10);
            //    if (service == null) //无住宿服务，移除住宿管理菜单
            //    {
            //        var menuList = new List<NavMenu>();
            //        foreach (var item in menus)
            //        {
            //            if (item.MenuID == 100203 || item.ParentID == 100203) continue;
            //            menuList.Add(item);
            //        }

            //        menus = menuList;
            //    }
            //}


            IList<TreeNode> nodes = new List<TreeNode>();
            ResolveMenuTree(menus, 0, nodes);

            if (nodes.Count > 0) nodes[0].Expanded = true;// 展开第一个树节点
            ViewBag.TreeMenuNodes = nodes.ToArray();// 视图数据
        }

        /// <summary>
        /// 生成菜单树
        /// </summary>
        /// <param name="menus"></param>
        /// <param name="parentMenuId"></param>
        /// <param name="nodes"></param>
        private int ResolveMenuTree(IEnumerable<NavMenu> menus, int? parentID, IList<TreeNode> nodes)
        {
            int count = 0;
            var list = menus.Where(m => m.ParentID == parentID).OrderByDescending(a => a.SortFlag).ThenBy(a => a.MenuID).ToList();
            foreach (var menu in list)
            {
                TreeNode node = new ();
                nodes.Add(node);
                count++;

                node.Text = menu.MenuName;
                if (!string.IsNullOrWhiteSpace(menu.Icon))
                {
                    //node.IconFont = menu.Icon.ParseEnumName<IconFont>();
                    node.IconFontClass = menu.Icon;
                }
                if (!string.IsNullOrEmpty(menu.Url))
                {
                    node.NavigateUrl = Url.Content(menu.Url);
                }

                if (menu.IsTreeLeaf)
                {
                    node.Leaf = true;

                    // 如果是叶子节点，但不是超链接，则是空目录，删除
                    if (String.IsNullOrEmpty(menu.Url))
                    {
                        nodes.Remove(node);
                        count--;
                    }
                }
                else
                {
                    int childCount = ResolveMenuTree(menus, menu.MenuID, node.Nodes);

                    // 如果是目录，但是计算的子节点数为0，可能目录里面的都是空目录，则要删除此父目录
                    if (childCount == 0 && String.IsNullOrEmpty(menu.Url))
                    {
                        nodes.Remove(node);
                        count--;
                    }
                }

            }

            return count;
        }

        #endregion

        public async Task<IActionResult> OnPostBtnSignOut_ClickAsync()
        {
            await HttpContext.SignOutAsync();
            HttpContext.Session.Clear();

            return RedirectToPage("/Login");
        }
    }
}